package com.dys.controller;

import com.dys.entity.Teacher;
import com.dys.service.TeacherService;
import com.dys.service.impl.TeacherServiceImpl;
import com.dys.util.PageUtil;
import com.google.gson.Gson;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Date;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: 疾风
 * @ClassName: TeacherServlet
 * @Description: 教师Servlet
 * @CreateDate: 2024/10/11
 * @Version: v1.0.0
 */
@WebServlet(urlPatterns = "/offlineSchool/teacherServlet.do")
public class TeacherServlet extends HttpServlet {
    private final TeacherService teacherService = new TeacherServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("listTeachersByPage".equals(method)) {
            listTeachersByPage(req, resp);
        } else if ("findTeacherByPoi".equals(method)) {
            findTeacherByPoi(req, resp);
        } else if ("deleteTeacherInfoByTid".equals(method)) {
            deleteTeacherInfoByTid(req, resp);
        } else if ("saveOneTeacherInfo".equals(method)) {
            saveOneTeacherInfo(req, resp);
        } else if ("findOneTeacherInfoByTid".equals(method)) {
            findOneTeacherInfoByTid(req, resp);
        } else if ("updateOneTeacherInfo".equals(method)) {
            updateOneTeacherInfo(req, resp);
        }
    }

    /**
     * 分页查询教师列表
     */
    protected void listTeachersByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("********分页查询教师信息**********");
        // 1.获取前端请求参数
        String teacherName = req.getParameter("teacherName");
        String phone = req.getParameter("phone");
        // 当前页
        int page = Integer.parseInt(req.getParameter("page"));
        System.out.println("当前页：" + page);
        // 2.定义每页显示3条记录
        int size = 3;
        System.out.println("每页展示条数：" + size);

        // 3.根据page、PageUtil工具类获得更多数据
        PageUtil pu = new PageUtil();
        // 设置page
        pu.setPage(page);
        // 设置size
        pu.setSize(size);
        // 获取startIndex
        int startIndex = pu.getStartIndex();
        System.out.println("当前索引值：" + startIndex);

        // 3.调用service层
        // 查询教师列表
        List<Teacher> list = teacherService.findTeachersByPage(startIndex, size, teacherName, phone);
        // 查询教师总数
        int count = teacherService.findTeacherCount();

        // 设置总条数
        pu.setTotalCount(count);
        System.out.println("总条数：" + count);
        // 设置总页数
        pu.setTotalPageCount();
        // 设置页码数组
        pu.setPageNums();
        // 获取页码数组
        int[] pageNums = pu.getPageNums();
        String s = "";
        for (int i = 0; i < pageNums.length; i++) {
            s += pageNums[i] + ",";
        }

        // 将数据放到分页工具类中
        pu.setList(list);

        // 4.响应给前端
        String json = new Gson().toJson(pu);
        list.stream().forEach(System.out::println);
        // 响应-因为前台发送的是ajax请求，所以这里响应的是json字符串
        resp.getWriter().println(json);
    }

    /**
     * 导出教师信息
     */
    protected void findTeacherByPoi(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("********利用POI导出学生信息**********");
        // 1.获取前端请求参数
        String teacherName = req.getParameter("teacherName");
        String phone = req.getParameter("phone");
        int page = Integer.parseInt(req.getParameter("page"));
        System.out.println("当前页：" + page);
        int size = 3;

        // 3.根据page、PageUtil工具类获得更多数据
        PageUtil pu = new PageUtil();
        // 设置page
        pu.setPage(page);
        // 设置size
        pu.setSize(size);
        // 获取startIndex
        int startIndex = pu.getStartIndex();
        System.out.println("当前索引值：" + startIndex);
        // 3.调用service层
        List<Teacher> list = teacherService.findTeachersByPage(startIndex, size, teacherName, phone);

        // 4.利用POI导出excel
        createExcel(list, resp);
    }

    /**
     * 创建Excel
     * 将内存中内容写入硬盘
     *
     * @param list 导出的数据
     */
    private static void createExcel(List<Teacher> list, HttpServletResponse resp) throws IOException {
        // 创建一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个工作表sheet
        HSSFSheet sheet = workbook.createSheet("教师表");
        // 控制列合并/行合并
        CellRangeAddress region = new CellRangeAddress(0, // 从第0行开始
                0, // 到第0行结束
                0, // 从第0列开始
                6 // 从第6列结束
        );
        sheet.addMergedRegion(region);


        // 在第0行第0列填入内容：教师信息
        HSSFRow hssfRow = sheet.createRow(0);
        HSSFCell headCell = hssfRow.createCell(0);
        headCell.setCellValue("教师信息");

        // 设置单元格格式居中
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setFillBackgroundColor(HSSFColor.GREEN.index);
        cellStyle.setFillForegroundColor(HSSFColor.GREEN.index);

        // 设置第0行的样式
        headCell.setCellStyle(cellStyle);


        // 添加表头行（创建第1行）
        hssfRow = sheet.createRow(1);
        // 添加表头内容（给第一行的每个cell设置内容）
        headCell = hssfRow.createCell(0);
        headCell.setCellValue("姓名");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(1);
        headCell.setCellValue("性别");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(2);
        headCell.setCellValue("爱好");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(3);
        headCell.setCellValue("出生日期");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(4);
        headCell.setCellValue("手机号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(5);
        headCell.setCellValue("描述");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(6);
        headCell.setCellValue("部门名称");
        headCell.setCellStyle(cellStyle);

        // 添加数据内容
        for (int i = 0; i < list.size(); i++) {
            hssfRow = sheet.createRow((int) i + 2);
            Teacher teacher = list.get(i);

            // 创建单元格，并设置值
            HSSFCell cell = hssfRow.createCell(0);
            cell.setCellValue(teacher.getTeacherName());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(1);
            cell.setCellValue(teacher.getSex());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(2);
            cell.setCellValue(teacher.getHobby());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(3);
            cell.setCellValue(teacher.getBirthDate());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(4);
            cell.setCellValue(teacher.getPhone());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(5);
            cell.setCellValue(teacher.getTeacherDesc());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(6);
            cell.setCellValue(teacher.getDepartment().getName());
            cell.setCellStyle(cellStyle);
        }

        // 保存Excel文件
        try {
            // OutputStream outputStream = new FileOutputStream("D:/students.xls");
            OutputStream out = resp.getOutputStream();
            String fileName = "teachers.xls";
            resp.setContentType("application/vnd.ms-excel");
            resp.setHeader("Content-disposition", "attachment; fileName=" + fileName);

            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据tid删除教师信息
     */
    protected void deleteTeacherInfoByTid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-----根据Tid删除教师信息-----");
        // 获取请求参数
        int tid = Integer.parseInt(req.getParameter("tid"));
        // 调用service层
        int rowCount = teacherService.deleteTeacherInfo(tid);
        System.out.println("删除时受影响行数：" + rowCount);
        // 响应-因为前台发送的是ajax请求，所以这里响应的是json字符串
        resp.getWriter().println(rowCount);
    }

    /**
     * 保存教师信息
     */
    protected void saveOneTeacherInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("********添加教师信息**********");
        // 1.获取前端请求参数
        String teacherName = req.getParameter("teacherName");
        String sex = req.getParameter("sex");
        String hobby = Arrays.toString(req.getParameterValues("hobby"));
        Date birthDate = java.sql.Date.valueOf(req.getParameter("birthDate"));
        String phone = req.getParameter("phone");
        String teacherDesc = req.getParameter("teacherDesc");
        int did = Integer.parseInt(req.getParameter("did"));
        System.out.println("部门编号："+did);

        // 2.封装为一个Teacher对象
        Teacher teacher = new Teacher(teacherName, sex, hobby, birthDate, phone, teacherDesc, did);

        // 3.调用service层
        int rowCount = teacherService.saveTeacherInfo(teacher);

        // 4.响应给前端
        resp.getWriter().println(rowCount);
    }

    /**
     * 保存教师信息
     */
    protected void findOneTeacherInfoByTid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-----查询单个教师信息-----");
        // 获取前端传递的请求参数
        int tid = Integer.parseInt(req.getParameter("tid"));
        System.out.println("教师tid: " + tid);
        // 调用service层
        Teacher oneTeacherInfo = teacherService.findOneTeacherInfo(tid);
        System.out.println("教师信息：" + oneTeacherInfo);
        // 处理爱好
        String[] hobbies = oneTeacherInfo.getHobby().replaceAll("\\[|\\]", "").split(", ");
        List<String> hobbyList = Arrays.asList(hobbies);
        // 将学生信息放入请求域中
        req.setAttribute("oneTeacherInfo", oneTeacherInfo);
        req.setAttribute("hobbyList", hobbyList);
        // 请求转发到修改页面
        req.getRequestDispatcher("/updateTeacher.jsp").forward(req, resp);
    }

    /**
     * 修改教师信息
     */
    protected void updateOneTeacherInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("-----修改单个教师信息-----");
        // 获取前端传递的请求参数
        int tid = Integer.parseInt(req.getParameter("tid"));
        System.out.println("教师tid: " + tid);
        String teacherName = req.getParameter("teacherName");
        String sex = req.getParameter("sex");
        String hobby = Arrays.toString(req.getParameterValues("hobby"));
        java.util.Date birthdate = java.sql.Date.valueOf(req.getParameter("birthDate"));
        String phone = req.getParameter("phone");
        String desc = req.getParameter("teacherDesc");
        int did = Integer.parseInt(req.getParameter("did"));

        // 封装Teacher对象
        Teacher teacher = new Teacher(tid, teacherName, sex, hobby, birthdate, phone, desc, did);

        // 调用service层
        int rowCount = teacherService.updateTeacherInfo(teacher);

        System.out.println("修改教师信息受影响行数：" + rowCount);
        // 响应给前端
        resp.getWriter().println(rowCount);
    }
}
